package com.epfresh.supplier.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.epfresh.api.entity.RequestEntityMapSupply;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.global.BaseApplication;
import com.epfresh.api.global.BaseFragment;
import com.epfresh.api.global.BuyerConstant;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.utils.JsonUtils;
import com.epfresh.api.utils.T;
import com.epfresh.api.widget.ptr.PtrDefaultHandler;
import com.epfresh.api.widget.ptr.PtrFrameLayout;
import com.epfresh.api.widget.ptr.PtrHandler;
import com.epfresh.supplier.R;
import com.epfresh.supplier.activity.AgencyListActivity;
import com.epfresh.supplier.activity.BaseProductDetailActivity;
import com.epfresh.supplier.activity.BaseStoreInfoActivity;
import com.epfresh.supplier.activity.GrouponInfoActivity;
import com.epfresh.supplier.activity.MakeAgentActivity;
import com.epfresh.supplier.activity.OrderAgentActivity;
import com.epfresh.supplier.adapter.HomeBuyerCityItemViewBinder;
import com.epfresh.supplier.adapter.HomeBuyerItemViewBinder;
import com.epfresh.supplier.adapter.HomeBuyerTitleViewBinder;
import com.epfresh.supplier.adapter.HomeBuyerTopViewBinder;
import com.epfresh.supplier.entity.AgencyListItem;
import com.epfresh.supplier.entity.BaseStoreInfo;
import com.epfresh.supplier.entity.ContentEntity;
import com.epfresh.supplier.entity.Groupon;
import com.epfresh.supplier.entity.HomeBuyer;

import java.util.ArrayList;
import java.util.List;

import multitype.MultiTypeAdapter;
import multitype.OnRecyclerViewItemClickListener;
import multitype.loadmore.LoadMoreDelegate;
import multitype.loadmore.LoadMoreItem;
import multitype.loadmore.LoadMoreViewBinder;

/**
 * @author wangzhanghuan
 * @Description
 * @version 1.0
 */
public class BaseStoreProductFragment extends BaseFragment {

    List<Object> mItems = new ArrayList<>();
    List<HomeBuyer> mHomeBuyers = new ArrayList<>();
    MultiTypeAdapter mMultiAdapter;
    //HomeBuyerTopViewBinder topViewBinder;
    HomeBuyerItemViewBinder itemViewBinder;
    HomeBuyerCityItemViewBinder itemBuyerCityViewBinder;
    LinearLayoutManager mManager;
    RecyclerView rv;

    LoadMoreDelegate loadMoreDelegate = new LoadMoreDelegate();

    int pageNum = -1;




    public String mBaseStoreId;
    public boolean mHasAgent = true;

    public String keywords;

    private BaseStoreInfo mBaseStoreInfo;
    private PtrFrameLayout ptrFrameLayout;

    private PtrHandler ptrHandler = new PtrHandler() {
        @Override
        public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
            return PtrDefaultHandler.checkContentCanBePulledDown(frame, rv, header);
        }

        @Override
        public void onRefreshBegin(PtrFrameLayout frame) {
            reqSupplyStoreDyn(0);
        }
    };

    private LoadMoreDelegate.LoadMoreSubject loadMoreSubject = new LoadMoreDelegate.LoadMoreSubject() {
        @Override
        public boolean canLoad() {
            return !ptrFrameLayout.isRefreshing() && pageNum > -1;
        }

        @Override
        public void onLoadMore() {

                loadMoreDelegate.setStatusLoading();
                reqSupplyStoreDyn(pageNum + 1);

        }
    };

    private void initHeadView(View v) {
        ptrFrameLayout = v.findViewById(R.id.fragment_ptr_home_ptr_frame);
        ptrFrameLayout.setPtrHandler(ptrHandler);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        return inflater.inflate(R.layout.fragment_base_store_product, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);


        initView(view);


        reqSupplyStoreDyn(0);
    }


    private void initView( View v) {

        rv = v.findViewById(R.id.rv_base_store);
        initHeadView(v);




        mManager = new LinearLayoutManager(getContext());

        rv.setLayoutManager(mManager);

        mMultiAdapter = new MultiTypeAdapter();
        LoadMoreViewBinder loadMoreViewBinder = loadMoreDelegate.getLoadMoreViewBinder();
        loadMoreDelegate.attach(rv, loadMoreSubject);

        itemBuyerCityViewBinder = new HomeBuyerCityItemViewBinder();
        itemBuyerCityViewBinder.setOnBuyerListener(new HomeBuyerCityItemViewBinder.OnBuyerListener() {
            @Override
            public void onBuyer(View view, int position, Groupon data) {
                intoGrouponInfo(data.getGrouponId(), data.getProductId(),data);
            }
        });
        itemViewBinder = new HomeBuyerItemViewBinder();
        itemViewBinder.setShowTitle(false);
        itemViewBinder.setOnBuyerListener(new HomeBuyerItemViewBinder.OnBuyerListener() {
            @Override
            public void onBuyer(View view, int position, HomeBuyer data) {


                intoGrouponInfo(null,data.getId(),null);
            }
        });
        itemViewBinder.setOnRecyclerViewItemClickListener(new OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, int position, Object data) {
                if (data instanceof HomeBuyer) {
                    switch (view.getId()) {
                        case R.id.rl_base:
                            HomeBuyer info = (HomeBuyer) data;
                            intoBaseStore(info.getBaseStoreId());
//                            T.toast(info.getBaseStoreId());
                            break;

                        case R.id.rl_product:

                            intoProductDetail((HomeBuyer) data);
                            break;
                    }
                } else {
                    return;
                }
            }
        });
/*
        topViewBinder = new HomeBuyerTopViewBinder();
        topViewBinder.setOnRecyclerViewItemClickListener(new OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, int position, Object data) {
                switch (view.getId()){
                    case R.id.tv_into_goods:
                        T.toast("info");
                        break;
                    case R.id.tv_order_agent:
                        Intent intent = new Intent(getAppActivity(), OrderAgentActivity.class);
                        intent.putExtra("orderType", 1);
                        startActivity(intent);
                        break;
                    case R.id.tv_order_together:
                        Intent tv_order_together = new Intent(getAppActivity(), OrderAgentActivity.class);
                        tv_order_together.putExtra("orderType", 0);
                        startActivity(tv_order_together);
                        break;
                    case R.id.tv_make_agent:
                        T.toast("tv_make_agent");
                        Intent makeAgent = new Intent(getAppActivity(), MakeAgentActivity.class);
                        startActivity(makeAgent);
                        break;
                }
            }
        });*/

        mMultiAdapter.register(LoadMoreItem.class, loadMoreViewBinder);
        //mMultiAdapter.register(String.class, topViewBinder);
        mMultiAdapter.register(HomeBuyer.class,itemViewBinder);
        mMultiAdapter.register(Groupon.class,itemBuyerCityViewBinder);

        rv.setAdapter(mMultiAdapter);

        mMultiAdapter.setItems(mItems);
    }

    private void intoGrouponInfo(String grouponId,String productId,final Groupon grouponBean ) {

        reqAgency(grouponId,productId,grouponBean);
    }
    protected void intoBaseStore(String baseStoreId) {
        Intent intent = new Intent(getContext(), BaseStoreInfoActivity.class);

        intent.putExtra("baseStoreId", baseStoreId);

        startActivity(intent);
    }

    private void intoProductDetail(HomeBuyer data) {
        Intent intent = new Intent(getContext(), BaseProductDetailActivity.class);

        intent.putExtra("mHasAgent",mHasAgent);
        intent.putExtra("baseStoreId", data.getBaseStoreId());
        intent.putExtra("productId", data.getId());
        startActivity(intent);
    }
    private void intoAgencyPage(String grouponId,String productId) {


        Intent intent = new Intent(getContext(), AgencyListActivity.class);
        //传递基地id
        intent.putExtra("storeId", mBaseStoreId);
        intent.putExtra("grouponId", grouponId);
        intent.putExtra("productId", productId);
        startActivity(intent);
    }


    private void intoGrouponInfoPage(String grouponId,String productId,AgencyListItem item) {


        Intent intent = new Intent(getContext(), GrouponInfoActivity.class);
        intent.putExtra("storeId", mBaseStoreId);
        intent.putExtra("grouponId", grouponId);
        intent.putExtra("productId", productId);
        intent.putExtra("agencyItem",JsonUtils.toJson(item));
        intent.putExtra("isSingle",true);
        startActivity(intent);
    }
    @Override
    public String getBaseTag() {
        return "";
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {


            case R.id.tv_apply_detail:

                break;
        }
    }



    private void reqSupplyStoreDyn(int pageNum) {
        if (getActivity() == null){
            return;
        }

        RequestEntityMapSupply RequestEntityMapSupply = new RequestEntityMapSupply();
        RequestEntityMapSupply.setCmd(BuyerConstant.CMD_BUYER_PRODUCT_LIST);
        RequestEntityMapSupply.putParameter("agentStoreId", BaseApplication.getInstance().getStoreId());
        RequestEntityMapSupply.putParameter("storeId", mBaseStoreId);
        RequestEntityMapSupply.putParameter("keyword", keywords);
        RequestEntityMapSupply.putParameter("pageNumber", pageNum);
        if(mHasAgent) {
            RequestEntityMapSupply.putParameter("hasAgent", 0);
        }else{
            itemViewBinder.isShowAgent = false;
        }
        RequestEntityMapSupply.putParameter("pageSize", 15);
        requestBuyer(RequestEntityMapSupply, BuyerConstant.CMD_BUYER_PRODUCT_LIST, onSupplyStoreDynRequestListener);
    }

    private OnRequestListener<ContentEntity<HomeBuyer>> onSupplyStoreDynRequestListener = new OnRequestListener<ContentEntity<HomeBuyer>>() {
        @Override
        public ContentEntity<HomeBuyer> jsonToObj(String responseStr) {
            return JsonUtils.fromJsonObject(responseStr, ContentEntity.class, HomeBuyer.class);

        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
            if (getActivity() == null){
                return;
            }
            ptrFrameLayout.refreshComplete();

        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
            if (getActivity() == null){
                return;
            }
            ptrFrameLayout.refreshComplete();

        }

        @Override
        public void onStart(Object tag) {
        }

        @Override
        public void onResponse(ResponseEntity<ContentEntity<HomeBuyer>> response, Object tag) {
            if (getActivity() == null){
                return;
            }
            ptrFrameLayout.refreshComplete();


            ContentEntity<HomeBuyer> responseElement = response.getResponseElement();


            boolean last = responseElement.getLast();

            int number = responseElement.getNumber();


            List<HomeBuyer> content = responseElement.getContent();

            //第一页
            if (number == 0) {
                mHomeBuyers.clear();
                mItems.clear();
            }
            pageNum = number;
            boolean isGrouponList = false;// TODO: 2018/6/14  
            if (content != null) {
                int size = content.size();
                for (int i=0;i<size;i++){

                    HomeBuyer homeBuyer = content.get(i);


                    List<Groupon> groupon = homeBuyer.getGroupon();
                    mHomeBuyers.add(homeBuyer);
                    mItems.add(homeBuyer);
                    if (groupon != null && homeBuyer.isCanGroupon()) {
                        int size1 = groupon.size();
                        if (size1 > 0) {
                            isGrouponList = true;// TODO: 2018/6/14  
                        }
                        for (int j = 0;j<size1;j++){
                            Groupon grouponItem = groupon.get(j);
                            grouponItem.setProductId(homeBuyer.getId());
                            grouponItem.setBaseStoreId(homeBuyer.getBaseStoreId());
                            grouponItem.setChargeUnit(homeBuyer.getChargeUnit());
                            if (j == size1-1){
                                grouponItem.setLast(true);
                            }else {
                                grouponItem.setLast(false);
                            }
                            mItems.add(grouponItem);
                        }

                    }
                }
            }

            if (mHomeBuyers.size() == 0) {
                loadMoreDelegate.setStatusEmpty();
                loadMoreDelegate.addLoadItemOnly(mItems);
            }else {
                loadMoreDelegate.addLoadItemOnly(mItems);
                //最后一个
                if (last) {
                    loadMoreDelegate.setStatusNoMore();
                } else {
                    loadMoreDelegate.setStatusNormal();
                }
            }
            mMultiAdapter.notifyDataSetChanged();

            // TODO: 2018/6/14  
            if (isGrouponList) {
                itemBuyerCityViewBinder.timerStart();
            } else {
                itemBuyerCityViewBinder.timerStop();

            }
        }
    };


    boolean isLockAgency;
    private void reqAgency(final String grouponId,final String productId, final Groupon grouponBean ) {
        if (isLockAgency){
            return;
        }
        isLockAgency = true;
        RequestEntityMapSupply data = new RequestEntityMapSupply();
        data.setCmd(BuyerConstant.CMD_BUYER_PRODUCT_AGENT_STORES);
        data.setClientIdentifierCode(getAppApplication().getClientIdentifierCode());
        data.setStoreId(BaseApplication.getInstance().getStoreId());

        data.putParameter("agentStoreId", BaseApplication.getInstance().getStoreId());
        data.putParameter("grouponId", grouponId);
        data.putParameter("productId", productId);


        requestBuyer(data, BuyerConstant.CMD_BUYER_PRODUCT_AGENT_STORES, new OnRequestListener<List<AgencyListItem>>() {
            @Override
            public List<AgencyListItem> jsonToObj(String responseStr) {
                return JsonUtils.fromJsonList(responseStr, AgencyListItem.class);
            }

            @Override
            public void onFail(int failCode, Object arg, Object tag) {
                isLockAgency = false;
                hideProgressDialog();
            }

            @Override
            public void onResponseError(int failCode, Object arg, Object tag) {
                hideProgressDialog();
                isLockAgency = false;
            }

            @Override
            public void onStart(Object tag) {

                showProgressDialog();
            }

            @Override
            public void onResponse(ResponseEntity<List<AgencyListItem>> response, Object tag) {
                List<AgencyListItem> responseElement = response.getResponseElement();
                hideProgressDialog();
                isLockAgency = false;
                    if (responseElement != null) {
                        if (grouponId == null) {//跳转到选择哪一个代办的页面
                            if (responseElement.size() == 1) {
                                AgencyListItem item = responseElement.get(0);
                                intoGrouponInfoPage(grouponId, productId,item);
                            } else if (responseElement.size() > 1) {
                                intoAgencyPage(grouponId, productId);
                            } else {
                                Toast.makeText(getAppActivity(), "该商品未找到代办店铺信息，请刷新后重试！", Toast.LENGTH_SHORT).show();
                            } 
                        } else {
                            if (responseElement.size() > 0) {
                                for (AgencyListItem item : responseElement) {
                                    if (item.getId().equals(grouponBean.getAgencyStoreId())) {
                                        intoGrouponInfoPage(grouponId, productId, item);
                                    }
                                }
                            } else {
                                //防止出现不能跳转的情况
                                intoAgencyPage(grouponId, productId);
                            }
                        }


       /*
                    if (responseElement.size() == 1) {
                        AgencyListItem item = responseElement.get(0);

                        intoGrouponInfoPage(grouponId, productId,item);
                    }else {
                        intoAgencyPage(grouponId, productId);
                    }*/
                }

            }
        });
    }



}
